package com.leesche.zcsp.node.web.controller.web.operation;

import com.leesche.zcsp.node.utils.*;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.model.PubDeviceShortCode;
import com.leesche.zcsp.node.web.model.PubPaymentURL;
import com.leesche.zcsp.node.web.service.PubDeviceShortCodeService;
import com.leesche.zcsp.node.web.service.PubPaymentURLService;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddQRCodeCommand;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import static com.leesche.zcsp.node.utils.UUIDGenerateUtil.generateShortUuid;

/**
 * Created by kaider on 2016/10/19.
 */
@Controller
@RequestMapping("/web/RQCode")
public class RQCodeController
{
    private final static Logger LOGGER = LoggerFactory.getLogger(RQCodeController.class);

    private static final String ADD_VIEW = "web/RQCode/addView";

    @Autowired
    private PrivilegeService privilegeService;
    @Autowired
    private PubPaymentURLService paymentURLService;
    @Autowired
    private PubDeviceShortCodeService codeService;

    private final static String destPath = PropKit.use("rqcode.properties").get("destPath");
    private static String zipFileName = UtilDate.getDate();


    //生成二维码页面
    @RequestMapping(value = "/addView", method = RequestMethod.GET)
    public String addView(){
        return ADD_VIEW;
    }

    /**
     * 生成设备二维码
     * @param command 二维码内容
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String, Object> add(
            AddQRCodeCommand command
    ){
        try {
            makeZipFile(command.getType(),command.getCodeNum());
            return WebResult.success().info("操作成功").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 检验需要下载的文件是否存在
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkFile/{type}", method = RequestMethod.GET)
    public Map<String, Object> checkFileIsNotNull(
            @PathVariable("type")int type
    ){
        try {
            Long adminId = privilegeService.getCurrentPrincipal().getUserid();
            File file= checkFile(type,adminId);
            if(file.exists()!=false){
                return WebResult.success().info("下载成功").toMap();
            }else{
                return WebResult.failure("文件不存在").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 执行下载操作
     * @param type
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/download/{type}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(@PathVariable("type")int type) throws IOException{
        Long adminId = privilegeService.getCurrentPrincipal().getUserid();
        File file = checkFile(type,adminId);
        String dfileName = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");

        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        headers.setContentDispositionFormData("attachment", dfileName);

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    /**
     * 生成zip文件
     * @param type 生成类型(1：设备二维码，2：支付二维码)
     * @param qrCodeNum 二维码数量
     * @throws Exception
     */
    private void makeZipFile(int type,int qrCodeNum) throws Exception{
        String qrCode = privilegeService.getCurrentPrincipal().getUserShortCode();
        Long adminId = privilegeService.getCurrentPrincipal().getUserid();
        zipFileName = UtilDate.getDate();
        switch (type){
            case 1:
                FileToZipUtil.deleteDirectory(destPath+adminId+"/device");
                String payCodeProp = PropKit.use("rqcode.properties").get("payCode1");
                for(int i=1;i<qrCodeNum+1;i++){
                    PubDeviceShortCode shortCode = new PubDeviceShortCode();
                    shortCode.setPrefix(qrCode);
                    shortCode.setAdminid(adminId);
                    shortCode.setShortcode(qrCode+generateShortUuid());
                    codeService.insert(shortCode);
                    String deviceCode = qrCode+shortCode.getShortcodeid();
                    QRCodeUtil.encode(deviceCode,destPath+adminId+"/device/"+zipFileName,true, deviceCode);
                    String payCode = "zf"+deviceCode;
                    QRCodeUtil.encode(payCodeProp.replace("PAYCODE",payCode).toString(), destPath+adminId+"/device/"+zipFileName,true, payCode);
                }
                //打包成zip文件
                FileToZipUtil.makeZipFile(destPath+adminId+"/device/"+zipFileName,zipFileName);
                break;
            case 2:
                String payCode1 = PropKit.use("rqcode.properties").get("payCode1");
                FileToZipUtil.deleteDirectory(destPath+adminId+"/pay");
                for(int i=0;i<qrCodeNum;i++){
                    PubPaymentURL paymentURL = new PubPaymentURL();
                    paymentURL.setAdminid(adminId);
                    paymentURL.setPaymenturlcode(UUIDGenerateUtil.generateUUID());
                    paymentURL.setDeviceid(adminId);
                    paymentURLService.insert(paymentURL);
                    qrCode = paymentURL.getPaymenturlid()+"";
                    QRCodeUtil.encode(payCode1.replace("PAYCODE",qrCode).toString(), destPath+adminId+"/pay/"+zipFileName,true,"zf"+qrCode);

                }
                FileToZipUtil.makeZipFile(destPath+adminId+"/pay/"+zipFileName,zipFileName);
                break;
            default:
                break;
        }
    }

    /**
     * 检查文件是否存在
     * @param type
     * @param adminId
     * @return
     */
    private File checkFile(int type,Long adminId){
        File file = null;
        zipFileName = UtilDate.getDate();
        switch (type){
            case 1:
                file = new File(destPath+adminId+"/device/"+zipFileName+"/"+zipFileName+".zip");
                break;
            case 2:
                file = new File(destPath+adminId+"/pay/"+zipFileName+"/"+zipFileName+".zip");
                break;
            default:
                break;
        }
        return file;
    }

    /**
     * 检查用户是否有用户简码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkUserShortCode", method = RequestMethod.GET)
    public Map<String,Object> checkUserShortCode(){
        try {
            String userShortCode = privilegeService.getCurrentPrincipal().getUserShortCode();
            if(StringUtils.isNotBlank(userShortCode)){
                return WebResult.success().info("操作成功").toMap();
            }else{
                return WebResult.failure("不存在").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

}